<template>
  <VueDraggable
    v-model="cloneList"
    :animation="150"
    handle=".handle"
    class="flex flex-col rounded min-h-3 pl-3"
    group="g1">
    <div v-for="(item, index) in cloneList" :key="item.id">
      <div
        class="h-50px hover:bg-gray-500/5 px-2 pt-2 pb-2 rounded flex items-center justify-between target"
        :class="{
          'pb-3': item.children.length > 0,
          'bg-gray-500/5 text-primary': item.id === currentCatalog?.id
        }">
        <img
          v-if="user.name"
          src="@/assets/images/addChild.png"
          class="w-6 h-6 handle cursor-pointer"
          :class="{ 'hidden-add': item.id !== currentCatalog?.id }"
          @click="addChild(item, index)" />
        <div class="flex items-center flex-1">
          <el-input type="text" v-model="item.name" v-if="!item.isSave && user.name" />
          <span class="flex-1" v-else @dblclick="dblclick(item)">{{ item.name }}</span>
          <img v-if="user.name" src="@/assets/images/move.png" class="w-6 h-6 handle cursor-move" />
          <img
            v-if="user.name"
            src="@/assets/images/delete.png"
            class="w-6 h-6 handle cursor-pointer"
            @click="remove(item, index)" />
        </div>
      </div>
      <draggable v-if="item.children" v-model:list="item.children"></draggable>
    </div>
  </VueDraggable>
</template>

<script setup lang="ts">
  import { VueDraggable } from 'vue-draggable-plus'
  import { v4 as uuidv4 } from 'uuid'
  import type { ICATALOG } from '@/types'
  import { useCatalogStore, useUserStore } from '@/stores'

  const cloneList = defineModel<Array<ICATALOG>>('list', { required: true })
  const currentCatalog = computed(() => useCatalogStore().catalog)
  const userStore = useUserStore()
  const user = computed(() => userStore.user)
  const remove = (item: ICATALOG, index: number) => {
    if (item.id === currentCatalog.value.id) {
      useCatalogStore().clearCatalog()
    }
    cloneList.value.splice(index, 1)
  }
  const addChild = (item: ICATALOG, index: number) => {
    if (currentCatalog.value?.isSave === false) {
      return ElMessage.error('请先保存内容')
    }
    if (!item.children) item.children = []
    const length = item.children.length
    item.children.push({
      name: `目录-${index + 1}-${length + 1}`,
      id: uuidv4(),
      children: [],
      isSave: false
    })
    useCatalogStore().setCatalog(item.children[item.children.length - 1])
  }
  const dblclick = (item: ICATALOG) => {
    if (currentCatalog.value?.isSave === false) {
      return ElMessage.error('请先保存内容')
    }
    item.isSave = false
    useCatalogStore().setCatalog(item)
  }
</script>

<style scoped>
  .hidden-add {
    visibility: hidden;
  }
  .target:hover .hidden-add {
    visibility: initial;
  }
</style>
